import { SchemaFormSearchContent } from "@/components/schema-form-render/components/schema-form-content";
import { initialSchemaSearch } from "@/components/schema-form-render/utils";
import { getPageMeta } from "@/services/request/meta";
import { getButtons } from "@/utils/with-btns";
import React, { useEffect, useState } from "react";
import { useScemaRender } from "../utils";
import { useSearchCache } from "./use-search-cache";

export interface WithSearchProps {
  pageCode: string;
  loading: boolean;
  handleSearch: (values: any, form: any) => void;
  path: string;
  needGroup?: boolean;
  events?: any;
  [propsName: string]: any;
}

const WithSearch: React.FC<WithSearchProps> = (props: WithSearchProps) => {
  const {
    pageCode,
    loading,
    handleSearch,
    needGroup = false,
    path,
    filedConfig = {},
    formConfigs = {},
  } = props;
  const [configs, setConfigs] = useState<any>(null);
  const hooksRef = React.useRef<any>();
  const F = React.useRef<any>();
  const { form, SchemaFormRender } = useScemaRender(filedConfig, formConfigs);
  F.current = form;
  useEffect(() => {
    useSearchCache(hooksRef, handleSearch, { form: F, path });
    getPageMeta(pageCode).then((res: any) => {
      if (res.success) {
        setConfigs(initialSchemaSearch(res.result, path, needGroup));
      }
    });
  }, []);
  // 生成搜索按钮
  const getSearchButtons = () => {
    if (configs && configs?.searchButtons) {
      return getButtons(
        { loading, buttons: (configs && configs?.searchButtons) || [] },
        hooksRef.current
      );
    }
    return null;
  };

  return configs ? (
    <SchemaFormSearchContent footer={getSearchButtons()}>
      <SchemaFormRender
        schema={configs?.schema}
        pageConfig={configs?.pageConfig}
      />
    </SchemaFormSearchContent>
  ) : null;
};

export default WithSearch;
